//
//  COConversationListCell.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit

private let font = UIFont.boldSystemFont(ofSize: PTW(14))

class COConversationListCell: RCMessageBaseCell {
    
    override init!(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUI()
    }
    
    func setUI(){
        baseContentView.addSubview(avaterImg)
        baseContentView.addSubview(contentLbl)
        baseContentView.addSubview(receiveImg)
        baseContentView.addSubview(translateBtn)
        messageTimeLabel.textColor = UIColor.colorWithHex("#C7C7C7")
        messageTimeLabel.font = UIFont.systemFont(ofSize: 12)
        messageTimeLabel.marginInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        // 头像点击
        avaterImg.addTap(tapHanlder: { ges in
            NotificationCenter.default.post(name: Notification.Name("chatEndEditingNotice"), object: nil)
        })
        receiveImg.addTap(tapHanlder: { ges in
            NotificationCenter.default.post(name: Notification.Name("chatEndEditingNotice"), object: nil)
            let photoView = MOPhotoPreviewer()
            photoView.preview(fromImageView: self.receiveImg, container: self.currentViewController()!.view)
        })
        self.addTap(tapHanlder: {ges in
            NotificationCenter.default.post(name: Notification.Name("chatEndEditingNotice"), object: nil)
        })
    }
    
    // 头像
    lazy var avaterImg: UIImageView = {
        let avater = UIImageView()
        avater.contentMode = .scaleAspectFill
        avater.layer.cornerRadius = PTW(20)
        avater.layer.masksToBounds = true
        avater.isHidden = true
        return avater
    }()
    
    // 文本内容
    lazy var contentLbl: COInsetLabel = {
        let content = COInsetLabel()
        content.textInsets = UIEdgeInsets(top: PTW(15), left: PTW(15), bottom: PTW(15), right: PTW(15))
        content.font = UIFont.boldSystemFont(ofSize: PTW(14))
        content.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        content.textColor = UIColor.colorWithHex("#2C255B")
        content.numberOfLines = 0
        content.lineBreakMode = .byWordWrapping
        content.isHidden = true
        return content
    }()
    
    // 收到的图片
    lazy var receiveImg: UIImageView = {
        let imageView = UIImageView()
        imageView.isHidden = true
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.backgroundColor = UIColor.colorWithHex("#F5F5F5")
        return imageView
    }()
    
    // 翻译
    lazy var translateBtn: UIButton = {
        let translate = UIButton()
        translate.setImage(KImaged("coco_msg_translate"), for: .normal)
        translate.isHidden = true
        translate.addTarget(self, action: #selector(tranlateAction), for: .touchUpInside)
        return translate
    }()
    
    override func setDataModel(_ model: RCMessageModel!) {
        super.setDataModel(model)
        updateLayout()
    }
    
    func updateLayout(){
        guard let _ = model else { return }
        if model.conversationType == .ConversationType_SYSTEM{
            avaterImg.image = KImaged("coco_msg_system")
        }else{
            if (self.messageDirection == .MessageDirection_RECEIVE){
                guard let cusId = kCustomerService.keyGetNSDefaultsKey() else{
                    RCIM.shared().userInfoDataSource.getUserInfo(withUserId: model.targetId, completion: { (userInfo) in
                        if let user = userInfo {
                            self.avaterImg.sd_setUrlImage(user.portraitUri, placeholder: KImaged("coco_icon_holder"))
                        }
                    })
                    return
                }
                if ((cusId as! String) == model.targetId){
                    self.avaterImg.image = KImaged("coco_msg_cusService")
                }else{
                    RCIM.shared().userInfoDataSource.getUserInfo(withUserId: model.targetId, completion: { (userInfo) in
                        if let user = userInfo {
                            self.avaterImg.sd_setUrlImage(user.portraitUri, placeholder: KImaged("coco_icon_holder"))
                        }
                    })
                }
            }
        }
        if let messageContent = model.content{
            if messageContent.isMember(of: RCTextMessage.self){
                self.contentLbl.isHidden = false
                self.receiveImg.isHidden = true
                // 文本消息
                let textMessage = messageContent as! RCTextMessage
                contentLbl.text = textMessage.content
                let labelSize = COConversationListCell.getContentMessageSize(direction: messageDirection, messageContent: messageContent)
                if messageDirection == .MessageDirection_RECEIVE{
                    self.avaterImg.isHidden = false
                    self.translateBtn.isHidden = false
                    
                    // 文本大小
                    contentLbl.frame = CGRect(x: PTW(70), y: 0, width: labelSize.width + PTW(30), height: labelSize.height + PTW(30))
                    // 头像大小
                    avaterImg.frame = CGRect(x: PTW(20), y: contentLbl.frame.maxY - PTW(40), width: PTW(40), height: PTW(40))
                    contentLbl.clipsCorners(corners: [.topRight,.bottomRight,.topLeft], radius: PTW(20))
                    translateBtn.frame = CGRect(x: contentLbl.right - PTW(10), y: contentLbl.bottom - PTW(30), width: PTW(40), height: PTW(40))
                }else{
                    self.avaterImg.isHidden = true
                    self.translateBtn.isHidden = true
                    // 文本大小
                    contentLbl.frame = CGRect(x: SCREENWIDTH - labelSize.width - PTW(50), y: 0, width: labelSize.width + PTW(30), height: labelSize.height + PTW(30))
                    contentLbl.clipsCorners(corners: [.topLeft,.bottomLeft,.topRight], radius: PTW(20))
                }
            }else if messageContent.isMember(of: RCImageMessage.self){
                self.contentLbl.isHidden = true
                self.receiveImg.isHidden = false
                self.translateBtn.isHidden = true
                let imageMessage = messageContent as! RCImageMessage
                let imageSize = COConversationListCell.getImageMessageSize(message: imageMessage)
                receiveImg.sd_setUrlImage(imageMessage.imageUrl, placeholder: KImaged("coco_pic_holder"))
                self.avaterImg.isHidden = true
                self.receiveImg.backgroundColor =  UIColor.colorWithHex("#F5F5F5")
                if messageDirection == .MessageDirection_RECEIVE{
                    // 头像大小
                    receiveImg.frame = CGRect(x: PTW(70), y: 0, width: imageSize.width, height:imageSize.height)
                    receiveImg.clipsCorners(corners: [.topRight,.bottomRight,.topLeft], radius: PTW(20))
                }else{
                    receiveImg.frame = CGRect(x: SCREENWIDTH - imageSize.width - PTW(20), y: 0, width: imageSize.width, height:imageSize.height)
                    receiveImg.clipsCorners(corners: [.topLeft,.bottomLeft,.topRight], radius: PTW(20))
                }
            }else if messageContent.isMember(of: COVideoContent.self){
                self.contentLbl.isHidden = false
                self.receiveImg.isHidden = true
                self.translateBtn.isHidden = true
                contentLbl.text = messageContent.conversationDigest()
                let labelSize = COConversationListCell.getContentMessageSize(direction: messageDirection, messageContent: messageContent)
                if messageDirection == .MessageDirection_RECEIVE{
                    self.avaterImg.isHidden = false
                    // 文本大小
                    contentLbl.frame = CGRect(x: PTW(70), y: 0, width: labelSize.width + PTW(30), height: labelSize.height + PTW(30))
                    avaterImg.frame =  CGRect(x: PTW(20), y: contentLbl.frame.maxY - PTW(40), width: PTW(40), height: PTW(40))
                    contentLbl.clipsCorners(corners: [.topRight,.bottomRight,.topLeft], radius: PTW(20))
                }else{
                    self.avaterImg.isHidden = true
                    // 文本大小
                    contentLbl.frame = CGRect(x: SCREENWIDTH - labelSize.width - PTW(50), y: 0, width: labelSize.width + PTW(30), height: labelSize.height + PTW(30))
                    contentLbl.clipsCorners(corners: [.topLeft,.bottomLeft,.topRight], radius: PTW(20))
                }
            }else if messageContent.isMember(of: COGiftContent.self){
                self.contentLbl.isHidden = true
                self.receiveImg.isHidden = false
                self.avaterImg.isHidden = true
                self.receiveImg.backgroundColor = .clear
                let imageMessage = messageContent as! COGiftContent
                receiveImg.sd_setUrlImage(imageMessage.cover, placeholder: KImaged("coco_msg_picture"))
                receiveImg.contentMode = .scaleAspectFit
                if messageDirection == .MessageDirection_SEND {
                    receiveImg.frame = CGRect(x: SCREENWIDTH - PTW(80) - PTW(20), y: 0, width: PTW(80), height:PTW(80))
               }
            }
        }
    }
    
    // 获取文本size
    class func getContentMessageSize(direction:RCMessageDirection,messageContent: RCMessageContent) -> CGSize {
        var content = String()
        if messageContent.isMember(of: RCTextMessage.self){
            let textMessage = messageContent as! RCTextMessage
            content = textMessage.content
        }else if messageContent.isMember(of: COVideoContent.self){
            content = messageContent.conversationDigest() ?? "[Video]"
        }
        guard content.count > 0 else { return .zero }
        // 文本最大宽度为
        let leftDis  = SCREENWIDTH - PTW(180)
        let rightDis = SCREENWIDTH - PTW(180)
        let maxWidth = direction == .MessageDirection_RECEIVE ? leftDis:rightDis
        let textRect = (content as NSString)
            .boundingRect(with: CGSize(width: maxWidth, height: 8000),
                          options: [.truncatesLastVisibleLine, .usesLineFragmentOrigin, .usesFontLeading],
                          attributes: [NSAttributedString.Key.font: font],
                          context: nil)
        // 这里宽度高度要取整数 不然会出现一条黑色的线条
        // 导致这个问题的原因是非整数的宽高导致的，像素高的机型会出现。
        // “ceil是表示向上取整,即向正无穷靠拢,而floor是向下取整,即向负无穷靠拢。
        return CGSize(width: ceil(textRect.size.width), height: ceil(textRect.size.height))
    }
    
    // 获取图片消息size
    class func getImageMessageSize(message: RCImageMessage) -> CGSize {
        return CGSize(width: PTW(180), height: PTW(240))
    }
    
    // 获取礼物消息size
    class func getGiftMessageSize(message: COGiftContent) -> CGSize {
        return CGSize(width: PTW(80), height: PTW(80))
    }
    
    // 自定义消息 Cell 的 Size
    override class func size(for model: RCMessageModel!, withCollectionViewWidth collectionViewWidth: CGFloat, referenceExtraHeight extraHeight: CGFloat) -> CGSize {
        guard let _ = model else { return CGSize.zero}
        if let content = model.content {
            if content.isMember(of: RCTextMessage.self){
                let textMessage = content as! RCTextMessage
                let size = COConversationListCell.getContentMessageSize(direction: model.messageDirection, messageContent: textMessage)
                var height = size.height + PTW(35)
                height = max(height, PTW(47))
                height += extraHeight
                return CGSize(width: collectionViewWidth, height: height )
            }else if content.isMember(of: RCImageMessage.self){
                let imageMessage = content as! RCImageMessage
                let size = COConversationListCell.getImageMessageSize(message: imageMessage)
                var height = size.height
                height += extraHeight
                return CGSize(width: collectionViewWidth, height: height )
            }else if content.isMember(of: COVideoContent.self){
                let videoMessage = content as! COVideoContent
                let size = COConversationListCell.getContentMessageSize(direction: model.messageDirection, messageContent: videoMessage)
                var height = size.height + PTW(35)
                height = max(height, PTW(47))
                height += extraHeight
                return CGSize(width: collectionViewWidth, height: height )
            }else if content.isMember(of: COGiftContent.self){
                let imageMessage = content as! COGiftContent
                let size = COConversationListCell.getGiftMessageSize(message:imageMessage)
                var height = size.height
                height += extraHeight
                return CGSize(width: collectionViewWidth, height: height )
            }
        }
        return CGSize(width: collectionViewWidth, height: extraHeight )
    }
    
    @objc func tranlateAction(){
        if let messageContent = self.model.content{
            if messageContent.isMember(of: RCTextMessage.self){
                let textMessage = messageContent as! RCTextMessage
                self.viewController()?.view.makeToast("translating...")
                var params:[String:Any] = [:]
                params["q"] = textMessage.content
                var languageCode = "en"
                if let currentLanguage = Locale.preferredLanguages.first {
                    if let range = currentLanguage.range(of: "-") {
                        languageCode = String(currentLanguage[currentLanguage.startIndex..<range.lowerBound])
                    }
                }
                params["target"] = languageCode
                COHttpManager.request(target: COBaseApi.translate(param: params), modelType: COTranslateResponseModel.self) {[weak self] code, object, success in
                    self?.viewController()?.view.hideToast()
                    if success == true{
                        if object?.response.code == 200 {
                            let translatedText = object?.response.translatedText
                            textMessage.content = translatedText ?? ""
                        }
                    }
                    self?.updateUiWithContent(txtMsg: textMessage)
                } failureBlock: { [weak self] code, msg in
                    self?.viewController()?.view.hideToast()
                    self?.viewController()?.view.makeToast("translate failed,try again later!")
                }
            }
        }
    }
    
    // 更新UI
    func updateUiWithContent(txtMsg:RCTextMessage){
        self.contentLbl.text = txtMsg.content
        let labelSize = COConversationListCell.getContentMessageSize(direction: self.messageDirection, messageContent: txtMsg)
        // 文本大小
        self.contentLbl.frame = CGRect(x: PTW(70), y: 0, width: labelSize.width + PTW(30), height: labelSize.height + PTW(30))
        self.contentLbl.clipsCorners(corners: [.topRight,.bottomRight,.topLeft], radius: PTW(20))
        self.translateBtn.isHidden = true
    }
    
}
